import React, { useEffect, useState, useMemo } from "react";
import "./index.less";
import MyTabbar from "@/components/MyTabbar";
import {
  getCartInfo,
  changeCartNum,
  changeItemSelected,
  delCartItem,
} from "@/api/cart";
import { Checkbox, Button, Stepper, Dialog } from "antd-mobile";
export default function Page() {
  // 购物车中所有的商品
  const [items, setItems] = useState<ItemType[]>([]);
  // 总数量
  const [number, setNum] = useState(0);
  // 总价格
  const [price, setPrice] = useState(0);
  const [delState, setDelState] = useState(false);
  // 全选状态
  const allChecked = useMemo(() => {
    return items.every((item) => item.selected);
  }, [items]);
  // 获取购物车数据的
  const fetchCartInfo = () => {
    getCartInfo().then((res) => {
      if (res.data.code === 0) {
        const { items, number, price } = res.data.data;
        setItems(items);
        setNum(number);
        setPrice(price);
      }
    });
  };
  useEffect(() => {
    fetchCartInfo();
  }, []);
  // 修改购物车商品购买数量
  const changeItemNumber = (key: string, number: number) => {
    changeCartNum({
      key,
      number,
    }).then((res) => {
      if (res.data.code === 0) {
        const { items, number, price } = res.data.data;
        setItems(items);
        setNum(number);
        setPrice(price);
      }
    });
  };
  // 修改商品选中状态
  const changeCartItemSelected = (key: string, selected: boolean) => {
    changeItemSelected({
      key,
      selected,
    }).then((res) => {
      if (res.data.code === 0) {
        const { items, number, price } = res.data.data;
        setItems(items);
        setNum(number);
        setPrice(price);
      }
    });
  };
  // 删除购物车商品
  const delItem = () => {
    // 确认框
    Dialog.confirm({
      title: "删除商品",
      content: "此操作会彻底删除该商品,继续吗?",
    }).then(() => {
      // 获取需要删除的 所有商品的key
      const selectedItems = items.filter((item) => item.selected);
      const keys: any[] = [];
      selectedItems.forEach((item) => {
        keys.push(item.key);
      });
      delCartItem({
        key: keys.join(',')
      }).then(res => {
        if (res.data.code === 0) {
          const { items, number, price } = res.data.data;
          setItems(items);
          setNum(number);
          setPrice(price);
        }
        // 如果全部删除
        if (res.data.code ===700){
          setItems([]);
          setNum(0);
          setPrice(0);
        }
      })
    });
  };
  // 点击全选 修改 所有商品选中状态
  const changeAllItemsSelected = (allChecked: boolean) => {
    // 获取所有的key
    const keys = [];
    items.forEach(item => {
      keys.push(item.key);
    })
    changeCartItemSelected(keys.join(','), allChecked)
  }
  return (
    <div className="cart-page">
      <div className="cart-head">
        <span>购买数量: {number}</span>
        <span
          onClick={() => {
            setDelState(!delState);
          }}
        >
          {delState ? "删除" : "管理"}
        </span>
      </div>
      <div className="cart-body">
        {items.map((item: ItemType) => {
          return (
            <div className="item" key={item.goodsId}>
              <Checkbox
                checked={item.selected}
                onChange={(checked) => {
                  changeCartItemSelected(item.key, checked);
                }}
              />
              <img src={item.pic} alt="" />
              <div className="item-info">
                <h4>{item.name}</h4>
                <p>价格: {item.price}</p>
                <Stepper
                  value={item.number}
                  min={1}
                  onChange={(value) => {
                    changeItemNumber(item.key, value);
                  }}
                />
              </div>
            </div>
          );
        })}
      </div>
      <div className="cart-foot">
        <div className="cart-foot-left">
          全选:
          <Checkbox checked={allChecked} onChange={(checked) => {
            changeAllItemsSelected(checked)
            
          }} />
          总价格: {price}
        </div>
        <div className="cart-foot-right">
          {delState ? (
            <Button color="danger" onClick={delItem}>
              删除
            </Button>
          ) : (
            <Button color="warning">立即下单</Button>
          )}
        </div>
      </div>
      <MyTabbar />
    </div>
  );
}
